package com.mis.geoEncryption.model.xml;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.mis.geoEncryption.model.data.clientData.ConnectToServerMessage;

public class XMLToObjectFactory {
	public static XMLToObjectFactory sharedInstance;
	
	public static XMLToObjectFactory getXMLToObjectFactoryInstance() {
		if(sharedInstance == null) {
			sharedInstance = new XMLToObjectFactory();
		}
		return sharedInstance;
	}
	
	public Object convertToObject(String xmlString) {
		Object outPutObj = null;
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(new ByteArrayInputStream(xmlString.getBytes("utf-8")));
			doc.getDocumentElement().normalize();
			String root = doc.getDocumentElement().getNodeName();
			System.out.println(root);
			if(root.equals("connectToServerMessage")) {
				outPutObj = new ConnectToServerMessage();
			}
			outPutObj = getObject(outPutObj, xmlString);
			return outPutObj;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	public Object getObject(Object object, String xmlString) {
		JAXBContext jaxbContext = null;
		try {
			jaxbContext = JAXBContext.newInstance(object.getClass());
			System.out.println(object.getClass());
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		 
		Unmarshaller jaxbUnmarshaller = null;
		try {
			jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		ByteArrayInputStream input = new ByteArrayInputStream (xmlString.getBytes());
		try {
			Object returnObj = jaxbUnmarshaller.unmarshal(input);
			return returnObj;
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}
